package com.example.fuluchou.service.impl;

import com.example.fuluchou.common.errorcode.ServiceErrorCodeConstants;
import com.example.fuluchou.common.exception.ServiceException;
import com.example.fuluchou.common.untils.*;
import com.example.fuluchou.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    //存放到 redis 中的手机验证码前缀为 verification_code_[phone]
    private static final String REDISPRE = "verification_code_";

    //设置redis的过期时间
    private static final int TIME = 120;
    private static final String TEMPLATECODE = "SMS_476715025";

    @Autowired
    private SMSUtil smsUtil;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String phone) {
        //校验手机号格式
        if(!RegexUtil.checkPhone(phone)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_ERROR);
        }
        //创建并发送短信
        String code = CaptchaUtil.getCode(4);
        Map<String,String> templateParam = new HashMap<>();
        templateParam.put("code",code);
        smsUtil.sendMessage(TEMPLATECODE,
                phone,
                JacksonUtil.writeValueAsString(templateParam));
        //同步到redis中
        redisUtil.set(REDISPRE+phone,code,TIME);
    }

    @Override
    public String getVerificationCode(String phone) {
        //校验手机号格式
        if(!RegexUtil.checkPhone(phone)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_ERROR);
        }
        return redisUtil.get(REDISPRE+phone);
    }

}
